import json
import re

from django.http import JsonResponse
from django.views import View
from django.core.cache import cache


from apps.app01 import models


class RegView(View):
    """注册"""

    authentication_classes = []

    def post(self, request):
        reg_dict = json.loads(request.body.decode())
        email = reg_dict['email']
        code = reg_dict['code']
        if reg_dict['password'] != reg_dict['con_password']:
            return JsonResponse({'code': 400, 'message': '密码与确认密码不符'}, status=400)
        for i in reg_dict['password']:
            if u"\u4e00" < i < u"\u9fff" or not reg_dict['password'].isalnum():
                return JsonResponse({'code': 402, 'message': '密码中含有特殊字符'}, status=402)
        if models.User.objects.filter(nickname=reg_dict['nickname']).exists():
            return JsonResponse({'code': 405, 'message': '用户名已存在'}, status=405)
        res = re.search("^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$", email)
        if not res:
            return JsonResponse({'code': 406, 'message': '邮箱格式不正确'})
        cache_code = cache.get(email)
        if not cache_code:
            return JsonResponse({'code': 407, 'message': '验证码已失效，请重新获取'}, status=407)
        if str(cache_code) != str(code):
            return JsonResponse({'code': 401, 'message': '验证码错误，请重新输入'}, status=401)
        cache.delete(email)
        cache.delete(code)

        user = models.User(nickname=reg_dict['nickname'], password=reg_dict['password'], email=reg_dict['email'])
        user.save()
        return JsonResponse({'code': 200, 'message': 'OK'}, status=200)
